package cn.zmx.editor;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;

import cn.zmx.service.File;

public class FileControllor extends HttpServlet implements File {
	
	//文件路径
	private String path;
	
	private BufferedWriter bw;
	
	private BufferedReader br;
	
	@Override
	public void init() throws ServletException {
		
		ServletContext context = getServletContext();
		
		String path = context.getInitParameter("path");
		
		try {
			bw = new BufferedWriter(new FileWriter(path,true));
			br = new BufferedReader(new FileReader(path));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String textarea = req.getParameter("textarea");
		
		req.setAttribute("s", textarea);
		
		write(textarea);
		
		read(textarea);
		
//		再转发到编辑界面,之前使用重定向，转发不了参数过去	？
		req.getRequestDispatcher("editor.jsp").forward(req, resp);
		
		//这次使用重定向，看参数如何转发过去
//		resp.setStatus(HttpServletResponse.SC_FOUND);
		
//		resp.setHeader("Location", "editor.jsp?name="+textarea);
		
	}
	
	//写文件进记事本
	@Override
	public void write(String textarea) {
			
		try {
			
			//改造下，每次多少字后换行
			bw.write(textarea);
	
			bw.write("\r\n");
			
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	
	//从记事本中读文件
	@Override
	public void read(String textarea) {
		
		try {
			//一次性读取一行
			String s = "";
			
			String count;
			
			while((count = br.readLine())!=null) {
				
				s= s + count +"\n";
				
//				System.out.println(count);
//				System.out.println(s);
			}

			//打印到网页上，那么把读取到的内容保存进服务器
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	
	//销毁里面，销毁文件指针
	@Override
	public void destroy() {
		
		try {
			br.close();
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
